<?php

namespace App\Http\Controllers\Api;
use App\Blocks\Activity;
use App\Http\Controllers\Controller;
use App\Libs\ResponseMessage;
use App\Models\Banners;
use App\Models\EatEveryDay;
use App\Models\EatEveryDayPrize;
use EasyWeChat\Factory;

class ActivityController extends Controller {

    public function getEatEveryDayGoods(){
        global $g_uid;
        $goods = EatEveryDay::where('status', 1)->orderBy('sort', 'asc')->get();

        foreach ($goods as $g){
            unset($g->probability);
            $g->img_url = env('APP_URL').$g->img_url;
        }

        $activityBlock = new Activity();
        $prize = $activityBlock->eatEveryDayPrizeList([],1, 20);

        $prizeText = [];
        foreach ($prize as $p){
            $prizeText[] = "用户{$p->nick_name}抽中{$p->grade}{$p->show_title}";
        }

        $myTodayPrize = EatEveryDayPrize::where('uid', $g_uid)->where('created_at', '>', date('Y-m-d', time()))->first();
        return response()->json(ResponseMessage::getInstance()->success(['goods' => $goods, 'prize' => $prize, 'myPrize' => $myTodayPrize, 'prize_text' => $prizeText])->response());
    }

    public function eatEveryDayRand(){
        global $g_uid;
        global $g_member;

//        if(!$g_member){
//            return response()->json(ResponseMessage::getInstance()->failed("NOT_MEMBER")->response());
//        }

        $goods = EatEveryDay::where('status', 1)->get();
        $noWin = EatEveryDay::where('id', 1)->first();

        $sumProbability = 0;
        foreach ($goods as $g){
            $sumProbability += $g->probability;
        }

        $win = null;

        if($sumProbability <= 0){
            $win = $noWin;
        }else {
            foreach ($goods as $g) {
                $randNum = mt_rand(1, $sumProbability);
                if ($randNum <= $g->probability) {
                    $win = $g;
                    break;
                } else {
                    $sumProbability -= $g->probability;
                }
            }
        }

        //中奖商品没有库存了
        if($win->stock_num <= 0){
            \Log::debug('没有库存了'.json_encode($win));
            $win = $noWin;
        }
        $win->img_url = env('APP_URL').$win->img_url;
        $redeemCode = getSalt(6);
        $win->redeem_code = $redeemCode;

        $activityBlock = new Activity();

        $status = $activityBlock->eatEveryDayPrize($g_uid, $win, getSalt(6));
        if($status === -1){
            return response()->json(ResponseMessage::getInstance()->failed("EAT_EVERY_DAY_ONLY_ONE")->response());
        }elseif($status === -2){
            return response()->json(ResponseMessage::getInstance()->failed('EAT_EVERY_DAY_NOT_START')->response());
        }elseif($status === false){
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }else {
            try {
                global $g_wx_openid;
                $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
                $app->template_message->send([
                    'touser' => $g_wx_openid,
                    'template_id' => '5uxnb9FqtoUnfHpz_7x_HLddywa_5LJJtBc1tUfjbTA',
                    'url' => env('APP_URL').'/api/wechat/login?redirect=eat_every_day',
                    'data' => [
                        'first' => '天天吃水果抽奖结果通知',
                        'keyword1' => $win->show_title,
                        'keyword2' => date('Y-m-d H:i:s', time()),
                        'remark' => '凭个人中奖记录到指定地点领取奖品，当日有效'
                    ],
                ]);
            }catch (\Exception $exception){
                \Log::error($exception);
            }
            return response()->json(ResponseMessage::getInstance()->success($win)->response());
        }
    }

    public function getBanner(){
        $banner = Banners::whereNull('deleted_at')
            ->orderBy('sort', 'desc')
            ->get();

        return response()->json(ResponseMessage::getInstance()->success($banner)->response());
    }

}